const app = getApp()
import Dialog from '../../dist/dialog/dialog';
const timeFormatting = require('../../utils/timeFormatting.js');
const CryptoJS = require('../../utils/aes-jia.js')
var timestamp = Date.parse(new Date()) / 1000;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    istwo:true,
    userInfo:{},
    id:'',
    list:[],
    pageNumber:1,
    pageSize:10,
    totalMoney:0.00,
    refundMoney:0.00,
    choice:false,
    listtype:1,
    whetherSetPayPwd:false,
    singleRefund:false,//单个退款框
    enrollment:'',//随行人数
    userList:[],//退款人id
    perCapita:'',//平均金额
    paymentAmount:'',//总金额
    inputRefund:'',//单个弹框输入
    amount:'',//总金额计算
    amount1: '',
    showPayPwdInput:false,//密码支付框
    pwdVal:'',//密码
    payFocus:true,//密码聚焦
    isstatus:'',//活动是否结束
    count:0,//全选个数
    define: true,//全选是否选中
    hiddenmodal:false,//一键退款弹框
    inputAmount:'',//一键退款金额
  },
  //列表切换
  listbtn(e){
    var that = this
    var type = e.currentTarget.dataset.id
    that.setData({
      listtype:type,
      pageNumber:1,
    })
    that.onShow()
  },
//收款列表
getList(){
  var that = this;
  app.req({
    url: "wechat/act/participation/participantListDetail",
    method: "post",
    data: {
      activityId: that.data.id,
      type: 2,
      pageNumber: that.data.pageNumber,
      pageSize: that.data.pageSize,
    },
    success: function (res) {
      if (200 == res.code) {
        that.setData({
          totalMoney: res.data.totalMoney,
          refundMoney: - res.data.refundMoney,
          list: that.data.list.concat(res.data.list.rows),
          totalPages: res.data.list.totalPages,
          isstatus: res.data.status,
        })
        console.log("费用列表", res)

      }
    }
  })
},
//退款列表
  getLists() {
    var that = this;
    app.req({
      url: "wechat/act/participation/participantListDetail",
      method: "post",
      data: {
        activityId: that.data.id,
        type: 5,
        pageNumber: that.data.pageNumber,
        pageSize: that.data.pageSize,
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            list: that.data.list.concat(res.data.list.rows),
            totalPages: res.data.list.totalPages,
          })
          console.log("退款列表", res)

        }
      }
    })
  },
//退款按钮
  ruturnbtn(e){
    var that = this
    if(that.data.istwo){
      that.setData({
        istwo:false
      })
    if (that.data.isstatus != 2) {
      wx.showToast({
        title: "活动未结束不可退款",
        icon: 'none',
        duration: 2000
      })
      return
    }
    console.log('id',e)
    var enrollment = e.currentTarget.dataset.enrollment
    var participantId = e.currentTarget.dataset.id
    var perCapita = e.currentTarget.dataset.percapita
    var paymentAmount = e.currentTarget.dataset.paymentamount
    that.data.userList.push(participantId)
    console.log('信息', enrollment, participantId, perCapita, that.data.userList)
    that.setData({
      singleRefund:true,
      enrollment: enrollment,
      perCapita: perCapita,
      paymentAmount: paymentAmount,
      inputRefund: perCapita,
      userList: that.data.userList,
      istwo:true
    })
    console.log('信息', that.data.userList)
  }
  },
  //单个退款框取消
  cancel(){
    var that = this
    that.setData({
      singleRefund: false,
      userList:[],
    })
  },
  //单个退款确定
  confirmRefund(){
    var that = this
    if (that.data.inputRefund > that.data.perCapita){
      wx.showToast({
        title: '退款金额不能大于人均金额',
        icon: 'none',
        duration: 2000
      })
      return
    } else if (that.data.inputRefund==''){
      wx.showToast({
        title: '请输入退款金额',
        icon: 'none',
        duration: 2000
      })
      return
    } else if (that.data.inputRefund==0){
      that.setData({
        singleRefund: false,
        userList: [],
      })
    } else {
      if (that.data.whetherSetPayPwd){
        that.setData({
          amount: that.data.inputRefund * (that.data.enrollment + 1),
          showPayPwdInput: true,
          singleRefund: false,
          amount1: that.data.inputRefund ,
        })
      } else {
        wx.showModal({
          title: '温馨提示',
          content: '为了您的账号安全，请设置支付密码',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/password/password',
              })
            }
          }
        })
      }
    }
  },
  //退款
  refund(){
    var that = this
    wx.request({
      url: app.globalData.url + "wechat/wxpay/refund?uid=" + that.data.userInfo.id + '&prepaymentRecordId=' + that.data.prepaymentRecordId,
      method: "post",
      header: {
        'api-client': '8693ece21a2711ea995200163e05ff66',
        'api-version': '1.3.1',
      },
      data: {
        activityId: that.data.id,
        refundWay: 0,
        amount: this.data.amount1,
        userList: that.data.userList
      },
      success: function (res) {
        if (200 == res.data.code) {
          console.log(res)
          wx.showToast({
            title: "退款成功",
            duration: 2000
          })
          that.onShow()
          that.setData({
            amount1:'',
            inputRefund: '',
            inputAmount:'',
            userList: [],
            define:true,
            count:0,
          })
        } else {
          that.setData({
            amount: '',
            inputRefund: '',
            inputAmount:'',
            userList: [],
            define: true,
            count: 0,
          })
          that.onShow()
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //全选
  allElectionClick(){
    var that = this
    if (that.data.list.length < 1) {
      wx.showToast({
        title: "暂无报名人员",
        icon: 'none',
        duration: 2000
      })
      return
    }
    var list = that.data.list
    var arr = []
    var count = 0
    if (that.data.define){
      for (var i = 0; i < list.length; i++) {
        list[i].flag = true;
        arr.push(list[i].participantId);
        count = count + (list[i].enrollment + 1)
      }
    }else{
      for (var i = 0; i < list.length; i++) {
        list[i].flag = false;
        arr=[];
        count=0
      }
    }
    that.setData({
      list:list,
      userList:arr,
      count:count,
      define: !that.data.define
    })
    console.log('全选', that.data.userList)
  },
  oneElectionClick(e){
    var that = this
    var index = e.currentTarget.dataset.index
    var arr = that.data.list
    var count = that.data.count
    if(arr[index].flag){
      arr[index].flag=false
      count = count - (arr[index].enrollment+1)
      that.remove(that.data.userList, arr[index].participantId);
      that.setData({
        count: count,
        userList: that.data.userList
      })
    }else{
      arr[index].flag=true
      count=count + (arr[index].enrollment + 1)
      that.data.userList.push(arr[index].participantId),
        that.setData({
          count: count,
          userList: that.data.userList
        })
    }
    if (that.data.userList.length==0 && !that.data.define){
      that.setData({
        define:true
      })
    }
    that.setData({
      list:arr
    })
    console.log('d单选',that.data.count,that.data.userList)
  },
  //一键退款
  oneKeyRefundClick(){
    var that = this
    if (that.data.list.length < 1) {
      wx.showToast({
        title: "暂无报名人员",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(that.data.count==0){
      wx.showToast({
        title: "请选择要退款的人员",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.isstatus != 2) {
      wx.showToast({
        title: "活动未结束不可退款",
        icon: 'none',
        duration: 2000
      })
      return
    }
    that.setData({
      hiddenmodal:true,
      inputAmount: that.data.list[0].perCapita
    })
  },
  //一键退款确定
  confirm(){
    var that = this
    console.log("金额", that.data.inputAmount)
    if (that.data.inputAmount > that.data.list[0].perCapita) {
      wx.showToast({
        title: '退款金额不能大于人均金额',
        icon: 'none',
        duration: 2000
      })
      return
    } else if (that.data.inputAmount == '') {
      wx.showToast({
        title: '请输入退款金额',
        icon: 'none',
        duration: 2000
      })
      return
    } else if (that.data.inputAmount == 0) {
      that.setData({
        hiddenmodal: false
      })
    }else{
      if (that.data.whetherSetPayPwd) {
        that.setData({
          amount: that.data.inputAmount * (that.data.count),
          showPayPwdInput: true,
          hiddenmodal: false,
          amount1: that.data.inputAmount,
        })
        that.getFocus()
      } else {
        wx.showModal({
          title: '温馨提示',
          content: '为了您的账号安全，请设置支付密码',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/password/password',
              })
            }
          }
        })
      }
    }
  },
  //一键退款取消
  cancel1(){
    this.setData({
      hiddenmodal:false,
      inputAmount:'',
    })
  },
//选择
  choiceTap(){
    var that = this
    that.setData({
      choice:true
    })
  },
  //预支付
  operationRecord() {
    let that = this
    var amounts = that.data.amount1
   
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + amounts)
    console.log('预支付参数', payPwd, amount, amounts)
    app.req({
      url: "wechat/wxpay/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: ''
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.refund()
        } else {
          that.setData({
            pwdVal: '',
            userList:[] 
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'wechat/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },



  inputBind: function (e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      console.log(1111111111111111111111111111)
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      e.detail.value = 500000
    }
    this.setData({
      inputAmount: e.detail.value
    })
  },


  inputBindSingle: function (e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      console.log(1111111111111111111111111111)
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      e.detail.value = 500000
    }
    this.setData({
      inputRefund: e.detail.value
    })
    console.log('退款', this.data.inputRefund)
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },

  //删除元素
  remove: function (array, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == val) {
        array.splice(i, 1);
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      id: options.id
    })
    app.getUserInfo(function (userInfo) {
      console.log("options第一次")
      that.setData({
        userInfo: userInfo
      })
      that.toggle("userInfo", userInfo);
    })
  },
//密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {
    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false,
      amount:'',
    })
  },
  /**
 * 获取焦点
 */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
 /**
   * 输入密码监听
   */
inputPwd: function (e) {
  this.setData({ pwdVal: e.detail.value });
  if (this.data.pwdVal.length >= 6) {
    this.setData({
      showPayPwdInput: false,
      payFocus: false
    });
    this.operationRecord()
  }
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.TestBuriedPoint2("yqlw_details_signup,yqlw_details_adopt,yqlw_details_examine,yqlw_details_refuse,yqlw_details_pv")
    this.setData({
      list:[],
      pageNumber:1,
      pageSize:10
    })
    if(this.data.listtype==1){
      this.getList()
    }else if(this.data.listtype==2){
      this.getLists()
    }
    this.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pageNumber:this.data.pageNumber+1
    })
    if (this.data.listtype == 1) {
      this.getList()
    } else if (this.data.listtype == 2) {
      this.getLists()
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})